package sky.dao.Impl;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import sky.dao.CountryDAO;
import sky.domain.Country;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Gauss
 * Date: 23.04.13
 * Time: 10:03
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class CountryDAOImpl implements CountryDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void addCountry(Country country) {
        sessionFactory.getCurrentSession().save(country);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Country> listCountry() {
        return sessionFactory.getCurrentSession().createQuery("from Country").list();
    }

    @Override
    public void removeCountry(Integer id) {
        Country country = (Country) sessionFactory.getCurrentSession().load(Country.class, id);
        if (null != country) {
            sessionFactory.getCurrentSession().delete(country);
        }
    }

    @Override
    public Country getCountryById(Integer id) {
        Country country = (Country) sessionFactory.getCurrentSession().get(Country.class, id);
        Hibernate.initialize(country.getCities());
        return country;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Country getCountryByName(String cityName) {
        Query query = sessionFactory.getCurrentSession().createQuery("from Country where name = ?");
        query.setParameter(0, cityName);
        return (Country) query.uniqueResult();
    }
}
